package cn.bookcycle.panda.pay.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * HTTP请求工具类
 *
 * @author liufenglin
 * @date 2018年1月29日
 */
public class Request {
	/**日志*/
	private  static final Logger logger = LoggerFactory.getLogger(Request.class);
	
	/**
	 * 发送GET请求
	 * 
	 * @param url 请求地址
	 * @param parameter 请求参数
	 * @return
	 */
	public static String sendGet(String url, String parameter) {
		// 请求发送后，接受到的返回信息
		String result = "";
		// 输入流
	    BufferedReader in = null;
		try {
			String urlNameString = url + "?" + parameter;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
//			e.printStackTrace();
			logger.info("给定的URI拒接连接！！！！！！");
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		} // end finally
		if ("".equals(result)) {
			// 如果没有任何返回，将result置为null，作为提示
			result = null;
		} else {}
		return result;
	 }
	
	/**
	 * 发送POST请求
	 * 
	 * @param url 请求地址
	 * @param parameter 请求参数
	 * @return
	 */
	public static String sendPost(String url, String parameter) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(parameter);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.warn("与post请求地址连接异常！！！！");
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		if ("".equals(result)) {
			// 如果没有任何返回，将result置为null，作为提示
			result = null;
		} else {}
		return result;
	}
	
	/**
	 * 发送https请求
	 * 
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（GET、POST）
	 * @param outputStr 提交的数据
	 * @param JSONObject Json数据
	 * 
	 * @throws IOException 
	 * @throws NoSuchProviderException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 */
	public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		String result = null;
		try{
			logger.info("进入https请求");
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] trustManager = {new PandaX509TrustManager()};
			logger.info("创建SSLContext对象");
			// 获得SSLContext的实例
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			logger.info("获得SSLContext");
			// 初始化
			sslContext.init(null, trustManager, new java.security.SecureRandom());
			// 得到SSLSocketFactory对象
			SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
			logger.info("得到SSLSocketFactory对象");
			// URL连接
			URL url = new URL(requestUrl);
			logger.info("URL连接");
			// 获得https连接
			HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
			httpsURLConnection.setSSLSocketFactory(sslSocketFactory);
			logger.info("获得https连接");
			// 是否输出
			httpsURLConnection.setDoOutput(true);
			// 是否输入
			httpsURLConnection.setDoInput(true);
			// 是否使用缓存
			httpsURLConnection.setUseCaches(false);
			// 设置请求方式
			httpsURLConnection.setRequestMethod(requestMethod);
			logger.info("https请求执行中。。。。");
			// 向输出流写数据
			if (outputStr != null){
				OutputStream outputStream = httpsURLConnection.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			
			// 从输入流读取返回内容
			InputStream inputStream =httpsURLConnection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			
			String str = "";
			StringBuffer stringBuffer = new StringBuffer();
			
			while ((str = bufferedReader.readLine()) != null){
				stringBuffer.append(str);
			}
			logger.info("https请求执行结束。。。。");
			// 释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			httpsURLConnection.disconnect();
			logger.info("https工具类中返回的SB：{}", stringBuffer);
			result = stringBuffer.toString();
			
		}catch (ConnectException ce){
			logger.error("https连接异常：{}", ce);
		}catch (Exception e){
			logger.error("异常:{}", e);
		}
		return result;
	}
}
